package com.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.RenewAction;
import com.bean.RecordBean;
import com.exception.DBException;
import com.exception.RenewException;
import com.exception.UserException;
import com.util.HandleInfo;
import com.util.Regex;
import com.util.StateInfo;

public class RenewServlet extends HttpServlet
{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setHeader("pragma", "no-cache");
		response.setHeader("cache-control", "no-cache");
		String option = request.getParameter("option");
		if ("checkr".equals(option))
		{
			String userID = request.getParameter("userID");
			if (null == userID || "" == userID || userID.length() != 8
					|| !Regex.checkUserID(userID))
			{
				HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
				return;
			}
			RecordBean recordBean = new RecordBean();
			recordBean.setUserID(userID);
			try
			{
				new RenewAction().getRenewInfo(response, recordBean);
			}
			catch (DBException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
			catch (RenewException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
			catch (UserException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
		}else
		if ("renew".equals(option))
		{
			String recordID = request.getParameter("recordID");
			String days = request.getParameter("days");
			if (null == recordID || "" == recordID || null==days || "".equals(days)
				|| !Regex.checkRecordID(recordID) || !Regex.checkDays(days))
			{
				HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
				return;
			}
			RecordBean recordBean = new RecordBean();
			recordBean.setRecordID(Integer.parseInt(recordID));
			recordBean.setDays(days);
			try
			{
				new RenewAction().renewIns(response, recordBean);
			}
			catch (DBException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
			catch (RenewException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
		}else
		{
			HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doGet(request, response);
	}
}
